﻿using System;
using System.Web.Mvc;
using System.Web;
using System.Data.Entity;
using Microsoft.Practices.Unity;
using Vit.Common;
using Vit.Common.Providers;
using Vit.Web;
using Vit.Web.Modules;
using Vit.Web.Providers;
using Vit.Web.Providers.DataSource;
using Vit.DynamicFormModule.Areas.Form.Models;
using Vit.DynamicFormModule.Areas.Form.DataProviders;

namespace Vit.DynamicFormModule.Areas.Form
{
    public class FormAreaRegistration : Vit.Web.Modules.AreaModuleBase
    {
        public override void OnApplicationStart(HttpApplication application, IUnityContainer unity)
        {
            base.OnApplicationStart(application, unity);
            ICacheProvider dataCache = unity.Resolve<ICacheProvider>();
            unity
                .RegisterInstance(new DynamicFormDb(), new HttpContextRequestLifetimeManager())
                // register enum datasources
                .RegisterInstance<IDataSourceProvider>("DataSource:FormActionType", new EnumDataSourceProvider(typeof(FormActionType), dataCache), new ContainerControlledLifetimeManager())
                // register data providers
                .RegisterType<IDataProvider<DynamicForm>, DynamicFormDataProvider>()
                .RegisterType<IDataProvider<FormField>, FormFieldDataProvider>()
                .RegisterType<IDataProvider<FormInput>, FormInputDataProvider>()
                .RegisterType<IDataProvider<InputValue>, InputValueDataProvider>();
     }

        public override bool OnInstalling(object sender, ModuleEventArg e, out string message)
        {
            message = string.Empty;
            try
            {
                DynamicFormDb db = new DynamicFormDb();
                return db.Database.CreateIfNotExists();
            }
            catch (Exception ex)
            {
                message = ex.GetBaseException().Message;
                return false;
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "Form_default",
                "Form/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional },
                new string[] { "Vit.DynamicFormModule.Areas.Form.Controllers" }
            );
        }

        public override string AreaName
        {
            get { return "Form"; }
        }
    }
}
